<?php
require_once __DIR__.'/admin/Bootstrap.php';
require __DIR__.'/site2/config/config.inc.php';
require_once __DIR__.'/site2/foundation/Templater.php';
require_once __DIR__.'/site2/includes/CheckOutMgr.class.php';
require_once __DIR__.'/site2/includes/CartMgr.class.php';
require_once __DIR__.'/site2/includes/CustomerMgr.class.php';
require_once __DIR__.'/site2/includes/OrderMgr.class.php';
require_once __DIR__.'/site2/includes/PaymentMgr.class.php';
require_once(MYSQL);

$_page = new CustomTemplater(__DIR__.'/site2/views/page/page.html');
include __DIR__.'/utils/prefix.php';
$_page->set("rightbar",null);

$checkoutMgr= new CheckOutMgr($dbc);
$cartMgr= new CartMgr($dbc);
$_main_content = new CustomTemplater(__DIR__.'/site2/views/checkout/address.html');

$errors=array();

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
	list($errors,$fn,$ln,$a1,$a2,$c,$s,$z,$p,$e)=$checkoutMgr->validateAddressForm();
	if (empty($errors)) 
	{
		$customerMgr=new CustomerMgr($dbc);	
		
		$cid=$customerMgr->addCustomer($e, $fn, $ln, $a1, $a2, $c, $s, $z, $p);
		$_SESSION['email']=$e;
		$_SESSION['customer_id']=$cid;
		if(isset($cid))
		{
			$orderMgr=new OrderMgr($dbc);	
			list($oid,$total)=$orderMgr->addOrder($uid, $cid);
			if (isset($oid, $total)) 
			{
				$_SESSION['order_id']=$oid;
				$paymentMgr=new PaymentMgr($dbc);
				$paymentMgr->addTransaction($oid, 'COD', $total,1 ,'No Payment',rand(),"WAITING TILL DELIVERY");
				header("Location: final.php");
				exit();
			}
				
		}	
	}
}

$_mini_cart=new CustomTemplater(__DIR__.'/site2/views/checkout/mini_cart.html');
$_mini_cart->set('uid',$uid);
$_mini_cart->set('cart',$cartMgr->getShoppingCartContents($uid));

$_main_content->setFormBuilder($errors);
$_main_content->set("minicart",$_mini_cart->parse());


$_page->set("content", $_main_content->parse());
$_page->publish();